package com.example.myapplication.function.musicmode

/**
 * 3. 主识别引擎
 */
class HummingRecognitionEngine {
    private val melodyAnalyzer = EnhancedMelodyAnalyzer()
    private val audioBuffer = mutableListOf<FloatArray>()

    var onRealTimeAnalysis: ((EnhancedMelodyAnalyzer.RealTimeAnalysis) -> Unit)? = null
    var onFinalResult: ((EnhancedMelodyAnalyzer.MelodyAnalysisResult) -> Unit)? = null

    // 在HummingRecognitionEngine中的完整初始化
    private val audioRecorder = AudioRecorder { audioData ->
        // 实时处理音频数据
        audioBuffer.add(audioData)

        // 保持缓冲区大小
        if (audioBuffer.size > MAX_BUFFER_SIZE) {
            audioBuffer.removeAt(0)
        }

        // 实时分析
        val realTimeResult = melodyAnalyzer.analyzeRealTime(audioData)
        realTimeResult?.let {
            onRealTimeAnalysis?.invoke(it)
        }

        // 定期完整分析
        if (audioBuffer.size % ANALYSIS_INTERVAL == 0) {
            performFullAnalysis()
        }
    }

    companion object {
        private const val MAX_BUFFER_SIZE = 1000 // 最大缓冲数量
        private const val ANALYSIS_INTERVAL = 10 // 每10个块分析一次
    }

    fun startRecognition() {
        audioBuffer.clear()

        audioRecorder.startRecording()
    }

    fun stopRecognition() {
        audioRecorder.stopRecording()
        performFinalAnalysis()
    }

    private fun performFullAnalysis() {
        if (audioBuffer.size < 10) return // 至少需要一些数据

        Thread {
//            val result = melodyAnalyzer.analyzeMelody(audioBuffer)
            // 可以在这里进行实时更新
        }.start()
    }

    private fun performFinalAnalysis() {
        Thread {
            val finalResult = melodyAnalyzer.analyzeMelody(audioBuffer)
            onFinalResult?.invoke(finalResult)
        }.start()
    }

    fun clearBuffer() {
        audioBuffer.clear()
    }
}